<template>
  <el-dialog
    v-dialogDrag
    :title="title"
    :visible.sync="visible"
    width="800px"
    append-to-body
  >
    <el-form ref="form" :model="form" label-width="auto" :rules="rules">      

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="项目名称" prop="name" class="person">
            <el-input
              v-model="form.name"
              placeholder="项目名称"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="选择药企" prop="companyList" class="person">
            <el-select v-model="form.companyList" placeholder="请选择">
              <el-option
                v-for="item in enterprisesList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="选择训练员" prop="trains" class="person">
           <el-select v-model="form.trains" multiple placeholder="请选择">
              <el-option
                v-for="item in doctors"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="选择审核员" prop="reviews" class="person">
            <el-select v-model="form.reviews" multiple placeholder="请选择">
              <el-option
                v-for="item in doctors"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>

          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始日期" prop="beginDate" class="person">
            <el-date-picker
              v-model="form.beginDate"
              type="date"
              placeholder="开始日期"
              value-format="yyyy-MM-dd"
              style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束日期" prop="endDate" class="person">
            <el-date-picker
              v-model="form.endDate"
              type="date"
              placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="评分标准" prop="scoreRuleList" class="person">
            <el-tag
              :key="tag.id"
              v-for="tag in form.scoreRuleList"
              closable
              :disable-transitions="false"
              @close="handleScoreRuleClose(tag)">
              {{tag.name}}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="scoreRuleInputVisible"
              v-model="scoreRuleInputValue"
              ref="saveScoreRuleInput"
              size="small"
              @keyup.enter.native="handleScoreRuleInputConfirm"
              @blur="handleScoreRuleInputConfirm"
            >
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showScoreRuleInput">+ 标签</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="标签" prop="labels" class="person">
            <el-tag
              :key="tag"
              v-for="tag in form.labels"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)">
              {{tag}}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="labelInputVisible"
              v-model="labelInputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 标签</el-button>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

  </el-dialog>
</template>

<script>
import BindDialog from '@/components/bindDialog/index.vue'
import { dialogFrame } from './frameData'
import { getEnterprisesList } from '@/api/enterprises'
import { addProject, modifyProject } from '@/api/trainProject'

const markForm = () => {
  return {
    name: "",
    beginDate: '',
    endDate: '',
    companyList: [],
    userList: [],
    scoreRuleList: [],
    labels: [],
    trains: [],
    reviews: []
  }
}

export default {
  name: "",
  components: {
    BindDialog
  },
  data() {
    return {
      rules: {
        name: [{ required: true, message: '项目名称是必填项', trigger: 'blur' }],
        companyList: [{ required: true, message: '选择药企是必填项', trigger: 'change' }],
        trains: [{ required: true, message: '选择训练员是必填项', trigger: 'change' }],
        reviews: [{ required: true, message: '选择审核员是必填项', trigger: 'change' }],
        beginDate: [{ required: true, message: '开始日期是必填项', trigger: 'change' }],
        endDate: [{ required: true, message: '结束日期是必填项', trigger: 'change' }],
        scoreRuleList: [{ required: true, message: '评分标准是必填项', trigger: 'blur' }],
        labels: [{ required: true, message: '标签是必填项', trigger: 'blur' }]
      },
      title: "",
      type: "",
      config: {
        edit: {
          func: modifyProject,
          title: "编辑"
        },
        new: {
          func: addProject,
          title: "新增"
        }
      },
      form: markForm(),
      visible: false,
      labelInputValue: "",
      labelInputVisible: false,
      scoreRuleInputValue: "",
      scoreRuleInputVisible: false,
      dialogFrame,
      query: '',
      loading: false,
      doctors: [],
      enterprisesList: []
    };
  },
  watch: {
    'form.companyList': {
      handler(newVal) {
        const currentProject = this.enterprisesList.find(item => item.value === newVal);
        this.updateTrainsAndReviews(currentProject);
      },
      immediate: false
    }
  },
  mounted() {
    this.queryEnterprisesAsync()
  },
  methods: {
    updateTrainsAndReviews(currentProject){
      if (currentProject && currentProject.userList && currentProject.userList.length > 0) {
        this.doctors = currentProject.userList.map(item => {
          return {
            label: item.name,
            value: item.id
          };
        });
      }
    },
    handleClose(tag) {
      this.form.labels.splice(this.form.labels.indexOf(tag), 1);
    },

    showInput() {
      this.labelInputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let labelInputValue = this.labelInputValue;
      if (labelInputValue) {
        this.form.labels.push(labelInputValue);
      }
      this.labelInputVisible = false;
      this.labelInputValue = '';
    },

    handleScoreRuleClose(tag) {
      this.form.scoreRuleList.splice(this.form.scoreRuleList.indexOf(tag), 1);
    },

    showScoreRuleInput() {
      this.scoreRuleInputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveScoreRuleInput.$refs.input.focus();
      });
    },

    handleScoreRuleInputConfirm() {
      let scoreRuleInputValue = this.scoreRuleInputValue;
      if (scoreRuleInputValue) {
        this.form.scoreRuleList.push({
          name: scoreRuleInputValue,
          sortNo: this.form.scoreRuleList.length + 1
        });
      }
      this.scoreRuleInputVisible = false;
      this.scoreRuleInputValue = '';
    },

    queryEnterprisesAsync(){
      getEnterprisesList({
          pageNum: 1,
          pageSize: 100,
      }).then(res => {
        if(res.rows && res.rows.length >= 0){
          this.enterprisesList = res.rows.filter(item => item.name).map(item => {
            return {
              label: item.name,
              value: item.id,
              userList: item.userList
            }
          })
        }
      })
    },

    showDialog(data) {
      this.reset();
      const isEdit = !!data;
      this.visible = true;
      this.type = isEdit ? "edit" : "new";
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
      if (isEdit) {
        const row = JSON.parse(JSON.stringify(data));
        const trains = []
        const reviews = []
        row.userList && row.userList.length > 0 && row.userList.forEach(element => {
          if(element.roleType === '0'){
            trains.push(element.id)
          }else{
            reviews.push(element.id)
          }
        });
        
        let companyList = []
        if(row.companyList && row.companyList.length > 0){
          companyList = row.companyList.map(item => {
            return item.id
          })
          companyList = companyList[0]
        }

        this.doctors = this.enterprisesList.filter(item => item.value === companyList)?.[0]?.userList
        if(this.doctors && this.doctors.length > 0){
          this.doctors = this.doctors.map(item => {
            return {
              label: item.name,
              value: item.id
            }
          })
        }

        row.labels = row.labelList

        this.form = {
          ...row,
          companyList,
          trains,
          reviews
        };
      }
      this.title = this.config[this.type].title;
    },

    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.visible = false;
          const trains = this.doctors.filter(item => {
            return this.form.trains.includes(item.value)
          }).map(item => {
            return {
              id: item.value,
              name: item.label,
              roleType: '0'
            }
          })

          const reviews = this.doctors.filter(item => {
            return this.form.reviews.includes(item.value)
          }).map(item => {
            return {
              id: item.value,
              name: item.label,
              roleType: '1'
            }
          })

          const companyList = this.enterprisesList.filter(item => item.value === this.form.companyList)

          const data = { 
            ...this.form, 
            userList: [...reviews, ...trains], 
            labels: JSON.stringify(this.form.labels), 
            companyList: companyList && companyList.length > 0 ? companyList.map(item => {
              return {
                id: item.value,
                name: item.label
              }
            }) : []
          }

          if(this.type === "new"){
            delete data.id;
          }else{
            delete data.userNum
            delete data.num
            delete data.createTime
          }

          delete data.reviews
          delete data.trains

          this.config[this.type]?.func(data).then(() => {
            this.$modal.msgSuccess("提交成功");
            this.visible = false;
            this.$emit("getTableList");
          });
        }
      });
    },

    cancel() {
      this.visible = false;
    },

    reset() {
      this.form = markForm();
      this.$forceUpdate();
    },

  },
};
</script>
<style scoped lang="scss">
.label-list{
  height: 36px;
  display: flex;
  align-items: center;

  .el-tag{
    margin-right: 10px;
  }

  .button-new-tag{
    height: 28px;
    padding: 0 20px;
  }

  .input-new-tag{
    width: 100px;
    height: 28px;
    display: flex;

    ::v-deep .el-input__inner {
      width: 100%;
      height: 100%;
    }
  }
}
.person{
  position: relative;

  .el-icon-user{
    position: absolute;
    top: 10px;
    right: 10px;
    cursor: pointer;
  }

  .cover{
    width: 100%;
    height: 100%;
    position:absolute;
    top: 0;
    left: 0;
    z-index: 1;
    cursor: pointer;

    &:hover {
      .el-input__inner{
        border-color: #C0C4CC;
      }
    }
  }
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
